<template>
  <div class="base-container" id="main">
    <t-steps :current="activeForm" status="process" :onChange="onCurChanged">
      <t-step-item v-for="(item,index) in stepList" :title="item.title" :key="index" :content="isSubmit(item.id)">

      </t-step-item>
    </t-steps>
    <t-loading text="加载中..." :fullscreen="false" attach="#main" :loading="applyLoading" size="medium">
    </t-loading>
    <t-form ref="form" :key="activeForm" label-align="top" :colon="true" v-if="activeForm === 0" class="step-form" :data="formData0"
            :rules="rules0"
            labelWidth="120px">
      <t-row style="flex: 1">
        <t-col :span="12">
          <t-form-item label="简要技术说明及主要技术性能指标" name="briefDescription">
            <tiny-mce-editor :key="activeForm" v-model="formData0.briefDescription"></tiny-mce-editor>
          </t-form-item>
          <t-form-item label="推广应用前景与措施" name="applicationProspect">
            <tiny-mce-editor :key="activeForm" v-model="formData0.applicationProspect"></tiny-mce-editor>
          </t-form-item>
          <t-form-item label="主要技术文件目录及来源" name="technicalDocument">
            <tiny-mce-editor :key="activeForm" v-model="formData0.technicalDocument"></tiny-mce-editor>
          </t-form-item>
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="11" >
          <t-button theme="primary" @click="onSubmit0()" >下一步</t-button>
        </t-col>
        <t-col :span="1" class="operation-container">
          <t-button variant="outline" @click="close">返回</t-button>
        </t-col>
      </t-row>
    </t-form>
    <!-- 单位信息 -->
    <div class="step-form" v-if="activeForm === 1">
      <div style="color:red">
         此处单位信息是从任务书同步过来的，无法进行新增删除操作。
      </div>
      <t-row style="flex: 1">
              <project-unit  ref="project-unit" v-model="formData1.unitList" :adviceFunding="adviceFunding"
                            :projectId="projectId" :editOpen="true"
                            :closeOp="true" 
                            phaseType="4"></project-unit>
      </t-row>

      <t-row>
        <t-col :span="11">
          <t-space :size="10">
          <t-button @click="onCurChanged(0)" theme="primary" variant="base">上一步</t-button>
          <t-button theme="primary" @click="onSubmit1" >下一步</t-button>
          </t-space>
        </t-col>
        <t-col :span="1" class="operation-container">
          <t-button variant="outline" @click="close">返回</t-button>
        </t-col>
      </t-row>
    </div>
    <!-- 研究人员 -->
    <div class="step-form" v-if="activeForm === 2">
      <div style="color:red">
         此处人员信息是从任务书同步过来的，无法进行新增删除操作。
      </div>
      <t-row style="flex: 1">
        <project-member ref="project-member"  v-model="formData2.memberList" :projectId="projectId" :editOpen="true" phaseType="4" fromType="acceptance"></project-member>
      </t-row>
      <t-row>
        <t-col :span="11" >
          <t-space :size="10">
            <t-button @click="onCurChanged(1)" theme="primary" variant="base">上一步</t-button>
            <t-button  theme="primary"  @click="onSubmit2(1)">暂存</t-button>
            <t-tooltip v-if="isOldProject === '1'" content="提交后不会进入审批流程">
              <t-button  theme="primary"  @click="onSubmit2(2)" >提交</t-button>
            </t-tooltip>
            <t-tooltip v-else content="提交后不可再编辑会进入审批流程">
              <t-button theme="primary" @click="onSubmit2(2)" >提交到单位管理员</t-button>
            </t-tooltip>
          </t-space>
        </t-col>
        <t-col :span="1" class="operation-container">
          <t-button variant="outline" @click="close">返回</t-button>
        </t-col>
      </t-row>
    </div>
  </div>
</template>

<script>
import TinyMceEditor from "@/components/TinyMceEditor/index.vue";
import projectMember from "../pm/components/project-member.vue";
import projectUnit from "../pm/components/project-unit.vue";

export default {
  name: "acceptance-opinion-apply",
  components:{
    TinyMceEditor,
    projectMember,
    projectUnit
  },
  data(){
    return {
      activeForm: 0,
      applyLoading: false,
      projectId: null,
      taskId: null,
      adviceFunding: 0,
      stepList: [
        {
          id: 'opinionId',
          title: '基本信息',
          require: true,
        },
        {
          id: 'companyId',
          title: '单位信息',
          require: true,
        },
        {
          id: 'memberId',
          title: '研究人员',
          require: true,
        },
      ],
      formData0: {
        briefDescription: '',
        applicationProspect: '',
        technicalDocument: ''
      },
      rules0: {
        briefDescription: [{
          required: true,
          message: "推广应用前景与措施不能为空",
        }],
        applicationProspect: [{
          required: true,
          message: "推广应用前景与措施不能为空",
        }],
        technicalDocument: [{
          required: true,
          message: "推广应用前景与措施不能为空",
        }]
      },
      formData1: {
        unitList: []
      },
      rules1: {},
      formData2: {
        memberList: []
      },
      rules2: {},
      isOldProject: '0'

    }
  },
  watch: {
    activeForm: {
      immediate: true,
      handler(val) {
        const targetEle = document.getElementById("main")
        if (targetEle) {
          const {pos, top} = targetEle.style;
          targetEle.style.position = 'relative';
          targetEle.style.top = '-100px';
          targetEle.scrollIntoView({behavior: 'smooth', block: 'start', inline: "nearest"});
          targetEle.style.top = top;
          targetEle.style.position = pos;
        }
      }
    }
  },
  created() {
    this.isOldProject = this.$route.query.isOldProject || '0';
    const projectId = this.$route.params && this.$route.params.taskId;
    if (!projectId) {
      this.$message.error("缺少项目id");
      return false;
    }
    this.projectId = projectId;
    this.taskId = projectId;
    const activeForm = Number(sessionStorage.getItem(`${this.taskId}-acceptance-opinion-activeForm`)) || 0;
    this.onCurChanged(activeForm, 0);
  },
  methods:{
    onCurChanged(cur, pre) {
      if (Number(cur) !== 0) {
        if (!sessionStorage.getItem(`${this.taskId}-acceptance-opinion-opinionId`)) {
          this.applyLoading = false;
          this.$message.error("基本信息还未提交")
          return false;
        }
      }
      this.applyLoading = true;
      if (Number(cur) === 0) {
        if (sessionStorage.getItem(`${this.taskId}-acceptance-opinion-opinionId`)) {
          const objId = Number(sessionStorage.getItem(`${this.taskId}-acceptance-opinion-opinionId`));
          this.$api.kjxm.acceptance.opinionGet(objId).then(response => {
            Object.assign(this.formData0, response.data);
            this.activeForm = cur;
            sessionStorage.setItem(`${this.taskId}-acceptance-opinion-activeForm`, cur);
            this.applyLoading = false;
          }).catch((e) => {
            this.applyLoading = false;
            this.$message.error(e.toString());
          });
        } else {
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-acceptance-opinion-activeForm`, cur);
          this.applyLoading = false;
        }
      }else if(Number(cur) === 1){
        this.activeForm = cur;
        sessionStorage.setItem(`${this.taskId}-acceptance-opinion-activeForm`, cur);
        this.applyLoading = false;
      }else if(Number(cur) === 2){
        this.activeForm = cur;
        sessionStorage.setItem(`${this.taskId}-acceptance-opinion-activeForm`, cur);
        this.applyLoading = false;
      }
    },
    isSubmit(name) {
      if (sessionStorage.getItem(`${this.taskId}-acceptance-opinion-${name}`)) {
        return '已提交'
      }
      return '未提交';
    },
    onSubmit0(){
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          this.applyLoading = true;
          if (!sessionStorage.getItem(`${this.taskId}-acceptance-opinion-opinionId`)) {
            this.$api.kjxm.acceptance.opinionAdd({
              ...this.formData0,
              projectId: this.projectId,
            }).then(response => {
              sessionStorage.setItem(`${this.taskId}-acceptance-opinion-opinionId`, response.data.id)
              this.$message.success("提交成功");
              this.onCurChanged(1)
            }).catch((e) => {
              this.applyLoading = false;
              this.$message.error(e.toString());
            });
          } else {
            this.$api.kjxm.acceptance.opinionUpdate({
              ...this.formData0,
              id: Number(sessionStorage.getItem(`${this.taskId}-acceptance-opinion-opinionId`)),
              projectId: this.projectId,
            }).then(response => {
              this.$message.success("提交成功");
              this.onCurChanged(1);
            }).catch((e) => {
              this.applyLoading = false;
              this.$message.error(e.toString());
            });
          }
        }
        else{
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      });
    },
    onSubmit1(){
      const isValidate = this.$refs["project-unit"].checkData2()
      if (!isValidate) {
        return false;
      }
      this.applyLoading = true;
      this.formData1.unitList = this.formData1.unitList.map(val => ({...val}))
      this.$api.kjxm.project.companyAdd(this.formData1.unitList).then(response => {
        this.$message.success('提交成功');
        sessionStorage.setItem(`${this.taskId}-acceptance-opinion-companyId`, this.formData1.unitList.length)
        this.onCurChanged(2)
      }).catch((e) => {
        this.applyLoading = false;
        this.$message.error(e.toString());
      });
    },
    onSubmit2(type){
      if(type === 1){
        this.applyLoading = true;
        this.$api.kjxm.project.memberAdd(this.formData2.memberList).then(response => {
          this.$message.success('暂存成功');
          sessionStorage.setItem(`${this.taskId}-acceptance-opinion-memberId`, this.formData2.memberList.length)
          this.applyLoading = false;
        }).catch((e) => {
          this.applyLoading = false;
          this.$message.error(e.toString());
        });
      }else {
        const isValidate = this.$refs["project-member"].checkData()
        if (!isValidate) {
          return false;
        }
        if (this.isOldProject === '1') {
          this.$api.kjxm.project.memberAdd(this.formData2.memberList).then(response => {
            this.$api.kjxm.acceptance.opinionOldSubmit({
              projectId: this.projectId,
              id: sessionStorage.getItem(`${this.taskId}-acceptance-opinion-opinionId`)
            }).then(response => {
              this.$message.success('提交成功');
              sessionStorage.setItem(`${this.taskId}-acceptance-opinion-memberId`, this.formData2.memberList.length)
              // loading = false
              this.close();
            }).catch((e) => {
              this.$message.error(e.toString());
            });
          }).catch((e) => {
            this.$message.error(e.toString());
          });
        }else {
          // let loading = false;
          const confirmDia = this.$dialog.confirm({
            header: "提交后不可再编辑会进入审批流程",
            body: `是否确认提交？`,
            // confirmBtn: {
            //   content: loading ? '提交中...' : '提交',
            //   theme: 'primary',
            //   loading,
            // },
            theme: "warning",
            onConfirm: ({e}) => {
              confirmDia.update({
                confirmBtn: {
                  loading: true,
                },
              })
              this.$api.kjxm.project.memberAdd(this.formData2.memberList).then(response => {
                this.$api.kjxm.acceptance.opinionSubmit({
                  projectId: this.projectId,
                  id: sessionStorage.getItem(`${this.taskId}-acceptance-opinion-opinionId`)
                }).then(response => {
                  this.$message.success('提交成功');
                  sessionStorage.setItem(`${this.taskId}-acceptance-opinion-memberId`, this.formData2.memberList.length)
                  confirmDia.destroy();
                  // loading = false
                  this.close();
                }).catch((e) => {
                  confirmDia.update({
                    confirmBtn: {
                      loading: false,
                    },
                  })
                  this.$message.error(e.toString());
                });
              }).catch((e) => {
                this.$message.error(e.toString());
              });
            },
          })
        }


      }

    },
    close() {
      this.applyLoading = false;
      setTimeout(() => {
        this.$tab.closeOpenPage({path: "/kjxm/acceptance/project-opinion-my"});
      }, 1000)
    },
  }
}
</script>

<style scoped>
.base-container {
  display: flex;
  flex-direction: column;
}
.step-form {
  padding: 0 24px;
  height: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
}
.t-row {
  margin-bottom: 14px;
}

.step-card {
  height: 100%;
  margin-bottom: 14px;
  padding-bottom: 14px;
}
</style>
